/***************************************************************************
 创建者: 华磊
 开始时间: 2019.1.16
 copyright: (C) 华友高科
 ***************************************************************************/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    tcpServer=NULL;
    newSocket=NULL;
    clientCount=0;
    receiveCommandCount=0;
    sendInfoCount=0;

    timer=new QTimer();
    connect( timer, SIGNAL(timeout()), this, SLOT(timeOut_slot()) );
    timer->start( 50 );
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_sendJson_clicked()
{
    sendSensorInfo();
}

void MainWindow::timeOut_slot()
{
    receiveData();
}

void MainWindow::on_pushButton_startServer_clicked()
{
    if(NULL!=tcpServer)
    {
        return ;
    }

    tcpServer = new QTcpServer;
    int port=ui->lineEdit_port->text().toInt();
    if(!tcpServer->listen(QHostAddress::Any,port))
    {
        qDebug() << "TcpManager Server Listen Port Error:" << tcpServer->errorString();
        return;
    }
    connect(tcpServer, SIGNAL(newConnection()),  this, SLOT(newConnectionSlot()));
    QMessageBox::information(NULL, "INFO", "服务器创建成功", QMessageBox::Yes );

}

void MainWindow::newConnectionSlot()
{
    clientCount++;
    ui->lineEdit_clientCount->setText(QString::number(clientCount));
    newSocket = new QTcpSocket;
    newSocket = tcpServer->nextPendingConnection();
    if(!newSocket->isValid())
    {
        return;
    }

    QString clientIP = newSocket->peerAddress().toString().remove(QRegExp("::ffff:"));
    qDebug() << "new Client IP:" << clientIP;

}

int MainWindow::receiveData()
{
    if(NULL==newSocket)
    {
        return -1;
    }
    QByteArray receiveByteArry = newSocket->readAll();
    newSocket->flush();
    if(receiveByteArry.isEmpty())
    {
        return -1;
    }

    ui->textEdit_receiveText->setText(receiveByteArry);

    //json处理
    QJsonParseError jsonError;
    QJsonDocument receiveJsonDoc = QJsonDocument::fromJson(receiveByteArry, &jsonError);
    if(jsonError.error != QJsonParseError::NoError || true==receiveJsonDoc.isNull())
    {
          qDebug() << "json error,"<<receiveJsonDoc;
          return -1;
    }
    QJsonObject redeiveJsonObj = receiveJsonDoc.object();

    //输出所有key，这一步是非必须的，放最后的话，你可能读不到任何key
    QStringList keys = redeiveJsonObj.keys();
    for(int i = 0; i < keys.size(); i++)
    {
//        qDebug() << "key" << i << " is:" << keys.at(i);
    }

    //因为是预先定义好的JSON数据格式，所以这里可以这样读取
    if(redeiveJsonObj.contains("cmd"))
    {
        if(1==process_manual_allSensorData(redeiveJsonObj))
        {

        }
    }
    return -1;



}

int MainWindow::sendSensorInfo()
{
    if(NULL==newSocket)
    {
        QMessageBox::information(NULL, "INFO", "没有客户端连接", QMessageBox::Yes );
        return -1;
    }
    //json 生成
    QJsonObject obj_root;
    QJsonObject obj_parameter;

    bool isSucess=ui->checkBox_isSucess->isChecked();
    obj_root.insert("issuc", QJsonValue(isSucess));
    obj_root.insert("errcode", QJsonValue(ui->lineEdit_errcode->text().toInt()));
    obj_root.insert("errdes", QJsonValue(ui->lineEdit_errdes->text()));
    obj_parameter.insert("distance", QJsonValue(ui->lineEdit_distance->text().toDouble()));
    obj_parameter.insert("angle", QJsonValue(ui->lineEdit_angle->text().toDouble()));
    obj_parameter.insert("d1", QJsonValue(ui->lineEdit_d1->text().toDouble()));
    obj_parameter.insert("d2", QJsonValue(ui->lineEdit_d2->text().toDouble()));
    obj_parameter.insert("offsetx", QJsonValue(ui->lineEdit_offsetx->text().toDouble()));
    obj_root.insert("rtval", obj_parameter);
    obj_root.insert("passWord", QJsonValue("123456"));
    QJsonDocument jsonDoc(obj_root);
    QByteArray tmpString=jsonDoc.toJson();
    qDebug()<<"sendSensorInfo tmpString="<<tmpString;

    ui->textEdit_sendText->setText(tmpString);

    //socket发送
    if(newSocket->state() != QTcpSocket::ConnectedState)
    {
        qDebug() << "sendSensorInfo error, socket 未连接:" << newSocket->errorString();
        return -1;
    }
    newSocket->write(tmpString);
    newSocket->flush();


    sendInfoCount++;
    ui->lineEdit_sendJsonCount->setText(QString::number(sendInfoCount));
    return 1;
}

int MainWindow::process_manual_allSensorData(QJsonObject &redeiveJsonObjIn)
{
    receiveCommandCount++;
    ui->lineEdit_receiveCommandCount->setText(QString::number(receiveCommandCount));

    if(true==ui->checkBox_isAutoSendJson->isChecked())
    {
        sendSensorInfo();
    }

//    dataOut.issuc=redeiveJsonObjIn.value("issuc").toBool();
//    dataOut.errcode=redeiveJsonObjIn.value("errcode").toInt();
//    QJsonObject subObj = redeiveJsonObjIn.value("rtval").toObject();
//    dataOut.d1=subObj["d1"].toDouble();
//    dataOut.d2 =subObj["d2"].toDouble();
//    if(false==subObj.contains("offsetx"))
//    {
//       qDebug()<<"json not contain offsetx";
//       return -1;
//    }
//    dataOut.offsetx=subObj["offsetx"].toDouble();
    return 1;
}

